package cn.kgc.novel.controller;

import cn.kgc.novel.common.Result;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;


//武龙
@Controller
public class OSSGetImgController {
    @RequestMapping("/upload")
    public String upload(@RequestParam(value = "file")MultipartFile file) throws IOException {
        if(file.isEmpty()){
            //获取URL过期时间
            Date expiration = new Date(new Date().getTime()+3600*1000);
            OSS ossClient = new OSSClientBuilder().build("oss-cn-beijing.aliyuncs.com","LTAI5tASx2stzLAfVkbPNv5d","NrCXTiKhoMtBsQf760rcZ5mEpN0Thk");
            String filename = "novel"+"/"+file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            PutObjectResult wulong01 = ossClient.putObject("wulong01", filename, inputStream);
            URL url = ossClient.generatePresignedUrl("wulong01",filename,expiration );
            String urlString = url.toString();
            ossClient.shutdown();
            return urlString;
        }else {
            return null;
        }
    }

    @RequestMapping("/getimg")
    public static String[] getImg(String[] imgname){
        if(imgname.length==0){
            return null;
        }
        OSS ossClient = new OSSClientBuilder().build("oss-cn-beijing.aliyuncs.com","LTAI5tASx2stzLAfVkbPNv5d","NrCXTiKhoMtBsQf760rcZ5mEpN0Thk");
        //获取URL过期时间
        Date expiration = new Date(new Date().getTime()+3600*1000);
        //生成URL
        for (int i = 0; i < imgname.length; i++) {
            URL url = ossClient.generatePresignedUrl("wulong01","novel/"+imgname[i],expiration );
            String urlString = url.toString();
            imgname[i] = urlString;
        }
        return imgname;
    }

}
